package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.UserLoginMapper;
import com.sky.mapper.addressMapper;
import com.sky.mapper.orderMapper;
import com.sky.mapper.shopCarMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.webSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Component
public class orderServiceImpl implements OrderService {
    @Autowired
    private orderMapper orderMapper;
    @Autowired
    private shopCarMapper shopCarMapper;
    @Autowired
    private shopCarMapper ShopCarMapper;
    @Autowired
    private addressMapper AddressMapper;
    @Autowired
    private UserLoginMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private webSocketServer websocketServer;


    /**
     * 用户下单
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO vo) {
        //地址为空
        AddressBook addressBook = AddressMapper.selectById(Math.toIntExact(vo.getAddressBookId()));
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //购物车为空
        List<ShoppingCart> page1 = shopCarMapper.page(BaseContext.getCurrentId());
        if(page1 == null || page1.isEmpty()){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Orders orders = new Orders();
        BeanUtils.copyProperties(vo, orders);
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName());
        //生成订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //订单时间
        orders.setOrderTime(LocalDateTime.now());
        //订单用户
        orders.setUserId(BaseContext.getCurrentId());
        //订单状态--待付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        //支付状态-未支付
        orders.setPayStatus(Orders.UN_PAID);
        //将订单插入订单表
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orderMapper.save(orders);
        Orders save = orderMapper.findById(Math.toIntExact(orders.getId()));
        //取出该用户的购物车信息
        List<ShoppingCart> page = shopCarMapper.page(BaseContext.getCurrentId());
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart shoppingCart : page) {
            shoppingCart.setId(null);
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(Long.valueOf(orders.getNumber()));
            list.add(orderDetail);
        }
        orderMapper.insertOrderDetail(list);

        //清空购物车
        shopCarMapper.deleteOne(new ShoppingCartDTO(),BaseContext.getCurrentId());
        OrderSubmitVO build = OrderSubmitVO.builder().orderAmount(vo.getAmount()).orderNumber(save.getNumber()).orderTime(save.getOrderTime()).id(save.getId()).build();
        return build;

    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        HashMap<String,Object> map=new HashMap<>();
        map.put("type",1);//1来单，2催单
        map.put("content","新增订单"+outTradeNo);
        map.put("orderId",outTradeNo);
        websocketServer.sendMessage(JSON.toJSONString(map));
    }

    /**
     * 取消订单
     */
    @Override
    public void cancel(Long id) throws Exception {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(id.toString());
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        Integer payStatus = ordersDB.getStatus();
        //根据订单id更新订单的状态、支付方式、支付状态、结账时间
        //0未支付 1已支付 2退款
        if(payStatus.equals(Orders.TO_BE_CONFIRMED)){
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderMapper.getListOrderDetailByOrderId(String.valueOf(orderId));

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    @Override
    public Result orderRemind(long id) {
        Orders byId = orderMapper.findById((int) id);
        HashMap<String,Object> map=new HashMap<>();
        long orderId= Long.parseLong(byId.getNumber());
        map.put("type",2);
        map.put("content","订单号："+orderId+"正在催单");
        map.put("orderId",orderId);
        websocketServer.sendMessage(JSON.toJSONString(map));
        return Result.success();
    }
}
